<template>
  <div v-if="!isMain && !isView">
    <px-scrollbar class="view-equip-detail">
      <div class="view-task-title">
        <px-button type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
        <div class="text">{{ taskDetailData.taskName }}</div>
        <div class="status">
          <div class="circle" :style="{ backgroundColor: `${tagBgColorList[taskDetailData.taskStatus]}` }" />
          <p :style="{ color: `${tagBgColorList[taskDetailData.taskStatus]}` }">
            {{ taskDetailData.taskStatusDesc }}{{ taskDetailData.timeOut ? "(超期)" : "" }}
          </p>
        </div>
      </div>
      <div class="view-equip-title">基础信息</div>
      <div class="view-equip-wrap">
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">点检任务编号</div>
            <div class="text">{{ taskDetailData.taskNo }}</div>
          </div>
          <div class="view-equip-item large">
            <div class="label">科室</div>
            <div class="text">{{ taskDetailData.classNameDesc }}</div>
          </div>
        </div>
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">系统</div>
            <div class="text">{{ taskDetailData.systemCodeDesc }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">设备编号</div>
            <div class="text">{{ taskDetailData.eqpId }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">设备名称</div>
            <div class="text">{{ taskDetailData.eqpName }}</div>
          </div>
        </div>
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">设备位置</div>
            <div class="text">{{ taskDetailData.positionName }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">任务分配</div>
            <div class="text">{{ taskDetailData.groupCodeName }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">任务开始时间</div>
            <div class="text">{{ taskDetailData.startTime }}</div>
          </div>
        </div>
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">任务结束时间</div>
            <div class="text">{{ taskDetailData.endTime }}</div>
          </div>
          <div class="view-equip-item large">
            <div class="label">任务宽泛期</div>
            <div class="text">{{ taskDetailData.taskLastTime }}</div>
          </div>
        </div>
      </div>
      <px-form ref="finishRef" :model="taskDetailData" label-position="right" label-width="100px">
        <div v-if="taskDetailData.contentList && taskDetailData.contentList?.length > 0">
          <div class="view-equip-title">点检内容</div>
          <EditDropDown :dropdownTitle="`${taskDetailData.eqpName}（${taskDetailData.eqpId}）`">
            <template v-slot:content>
              <SubEditDropDown
                v-for="(ruleItem, ruleIndex) in taskDetailData.contentList"
                :key="`SubEditDropDown${ruleIndex}`"
                :dropdownTitle="`${ruleItem.checkContentName}`"
              >
                <template v-slot:content>
                  <LazyRender>
                    <px-table
                      :data="ruleItem.pointCheckContentItemList"
                      style="margin-bottom: 18px"
                      class="equip-table inner-table"
                      size="small"
                      max-height="400"
                      border
                    >
                      <px-table-column
                        v-for="(item, colIndex) in tableColumns"
                        :key="`table${colIndex}`"
                        :label="item.label"
                        :prop="item.prop"
                        :min-width="item.minWidth"
                        :align="item.align"
                        :show-overflow-tooltip="item.showOverflowTooltip"
                        :fixed="item.fixed"
                      />
                      <px-table-column label="巡检结果" min-width="300" fixed="right">
                        <template #header>
                          <div>
                            <label class="must">巡检结果</label>
                          </div>
                        </template>
                        <template #default="scope">
                          <TaskFormAction
                            v-model:itemValue="taskDetailData.contentList[ruleIndex].pointCheckContentItemList[scope.$index].result"
                            :validated="validated"
                            :itemProps="['contentList', ruleIndex, 'pointCheckContentItemList', scope.$index, 'result']"
                            :formValue="taskDetailData"
                            :statusRange="scope.row.checkContentRangeValue"
                            :status="scope.row.checkContentRange"
                          />
                          <!-- <template v-if="scope.row.checkContentRange">
                            <px-form-item ref="formItemRef" label="" label-width="0px" :inline-message="true">
                              <div class="form-item-content">
                                <px-input
                                  v-if="scope.row.checkContentRange === 1"
                                  v-model="scope.row.result"
                                  class="cell-action"
                                  maxLength="200"
                                  placeholder="请输入"
                                  @change="handleChange"
                                />
                                <px-input-number
                                  v-if="scope.row.checkContentRange === 2"
                                  v-model="scope.row.result"
                                  class="cell-action"
                                  style="width: 100%"
                                />
                                <px-radio-group v-if="scope.row.checkContentRange === 3" v-model="scope.row.result" class="cell-action">
                                  <px-radio v-for="(item, index) in getOptions(scope.row.checkContentRangeValue)" :key="index" :label="item.value">{{
                                    item.label
                                  }}</px-radio>
                                </px-radio-group>
                                <px-select
                                  v-if="scope.row.checkContentRange === 4"
                                  v-model="scope.row.result"
                                  filterable
                                  class="cell-action"
                                  style="width: 100%"
                                  placeholder="请选择"
                                >
                                  <px-option
                                    v-for="(item, index) in getOptions(scope.row.checkContentRangeValue)"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.value"
                                  />
                                </px-select>
                              </div>
                            </px-form-item>
                          </template> -->
                        </template>
                      </px-table-column>
                    </px-table>
                  </LazyRender>
                </template>
              </SubEditDropDown>
            </template>
          </EditDropDown>
        </div>
        <div style="margin-top: 20px" class="view-equip-title">异常上报</div>
        <px-col :span="24">
          <px-form-item label="异常照片" prop="images">
            <PhotoUpload
              :photoType="'add'"
              :photoData="{ moduleName: moduleName }"
              :photoList="taskDetailData.images"
              style="margin-bottom: 18px"
              @changePhotoList="changePhotoList"
              @savePhotoStatus="savePhotoStatus"
            />
          </px-form-item>
        </px-col>
        <px-col :span="24">
          <px-form-item label="备注" prop="unnormalReport">
            <px-input
              v-model="taskDetailData.unnormalReport"
              type="textarea"
              placeholder="请输入备注"
              :autosize="{ minRows: 2, maxRows: 4 }"
              maxlength="1000"
              clearable
            />
          </px-form-item>
        </px-col>
      </px-form>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="emits('backMainPage')">取消</px-button>
      <px-button type="primary" :disabled="photoStatusFlag" @click="handleSubmit(finishRef)">完成并提交</px-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { detailExceptionTask, finishExceptionTask, getTaskModuleName } from "@/api/equip/exception";
import LazyRender from "@/components/LazyRender/index.vue";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import SubEditDropDown from "@/views/erc/inspect/components/SubEditDropDown.vue";
import TaskFormAction from "@/views/erc/inspect/task/components/TaskFormAction.vue";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs, watchEffect } from "vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["userId", "taskNo", "isMain", "isView", "isFresh"]);

// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);

const tagBgColorList = {
  0: "#909399", // 取消
  1: "#F59E0B", // 待接单
  2: "#3B82F6", // 执行中
  3: "#10B981" // 已完成
};

const finishRef = ref();
const validated = ref(false);

const state = reactive<any>({
  taskDetailData: "",
  moduleName: "",
  tableColumns: [
    { prop: "checkItem", label: "巡检项", minWidth: "200", showOverflowTooltip: true },
    { prop: "checkContent", label: "巡检内容", minWidth: "200", showOverflowTooltip: true }
  ],
  photoStatusFlag: false,
  formValue: {}
});

const { taskDetailData, moduleName, tableColumns, photoStatusFlag, formValue } = toRefs(state);

// 获取getModuleName
const getModuleNameValue = async () => {
  const data = await getTaskModuleName();
  moduleName.value = data;
};

// 执行结果变化
const handleChange = (value: any, ruleIndex: number, scopeIndex: number, scopeValue) => {
  taskDetailData.value.contentList[ruleIndex].pointCheckContentItemList[scopeIndex].result = value;
};

function transformFormToSave() {
  let taskContentItemDTOList = [];
  taskDetailData.value.contentList?.forEach(checkJobContentItem => {
    if (checkJobContentItem.pointCheckContentItemList) {
      checkJobContentItem.pointCheckContentItemList.forEach(checkContentItem => {
        taskContentItemDTOList.push({
          checkTaskNo: props.taskNo,
          eqpId: taskDetailData.value.eqpId,
          checkContentName: checkJobContentItem.checkContentName,
          ...checkContentItem
        });
      });
    }
  });
  taskDetailData.value.taskContentItemDTOList = taskContentItemDTOList;
}

// 新的图片列表
const changePhotoList = val => {
  console.log(val);
  taskDetailData.value.images = val;
};
// 图片是否上传完，是否可以保存
const savePhotoStatus = val => {
  photoStatusFlag.value = val;
};

watchEffect(async () => {
  if (!props.isView && !props.isMain) {
    getModuleNameValue();
    // 获取执行点检任务的详情
    const taskRes = await detailExceptionTask(props.taskNo);
    const { images } = taskRes;
    if (images?.length > 0) {
      images?.forEach(item => {
        item.url = item.fileUrl;
      });
      taskRes.images = taskRes.images;
    } else {
      taskRes.images = [];
    }
    taskDetailData.value = { ...taskRes, images };
  }
});

/** 提交按钮 */
const handleSubmit = async (formEl: any) => {
  transformFormToSave();
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const { images, id, unnormalReport, taskContentItemDTOList } = taskDetailData.value;
      const imgList = [];
      if (images && images?.length > 0) {
        images?.forEach(item => {
          if (item?.id) {
            imgList.push(item.id);
          } else if (item?.response.data.id) {
            imgList.push(item.response.data.id);
          }
        });
      }
      await finishExceptionTask({ id, taskNo: props.taskNo, unnormalReport, taskContentItemDTOList, photoIds: imgList });
      PxMessage.success("执行结果提交成功");
      emits("backMainPage");
      emits("queryTable");
    }
  });
};

const backMainPage = () => {
  if (props.isFresh) {
    emits("queryTable");
  }
  emits("backMainPage");
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/view-detail.scss");

.view-equip-detail {
  padding: 24px;
  height: calc(100vh - 186px);

  .view-task-title {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 20px;

    .text {
      margin-right: 8px;
      margin-left: 16px;
      font-size: 20px;
      font-weight: 600;
      line-height: 1;
      color: rgb(0 0 0 / 90%);
    }

    .status {
      display: flex;
      flex-direction: row;
      align-items: center;
      line-height: 1;

      .circle {
        width: 8px;
        height: 8px;
        margin-right: 5px;
        border-radius: 50%;
      }
    }
  }

  :deep(.inner-table) {
    width: 100%;

    .px-table__header thead tr th {
      font-size: 14px;
      font-weight: bold;
      color: #000;
      background-color: #e7eefb !important;
    }

    td.px-table__cell div {
      width: 100%;
    }
  }

  :deep(.inspect-task-detail-content) {
    width: 100%;
    min-width: 500px;
  }

  :deep(.px-table__header) {
    .must::before {
      margin-right: 4px;
      color: var(--px-color-danger);
      content: "*";
    }
  }
  .equip-table {
    :deep(tbody .px-table__cell) {
      padding: 0;
      height: 64px;
      line-height: 64px;
      .cell {
        height: 64px;
        line-height: 64px;
        .px-form-item {
          padding-top: 16px;
        }
      }
    }
  }
}

.info-form-btns {
  position: absolute;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  height: 68px;
  padding-right: 24px;
  background: #fff;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
}
</style>
